﻿/*
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
namespace Scaffold
{
    public class ScaffoldControllerFactory : DefaultControllerFactory
    {

        protected override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {

            RequestContext = requestContext;
            Type controllerType = this.GetControllerType(controllerName);
            IController ctlr = null; 

            var entry = ScaffoldApplication.FindEntity(controllerName);
            if (controllerType == null)
            {
                if (entry == null)
                {
                    throw new InvalidOperationException("No Such Controller");
                }
                else
                {
                    controllerType = typeof(ScaffoldController<>).MakeGenericType(entry.ItemType);
                    object instance = Activator.CreateInstance(controllerType);
                    controllerType.GetProperty("DataContext").SetValue(instance, Activator.CreateInstance(ScaffoldApplication.DataContextType), null);
                    ctlr = (IController) instance;

                }
            }
            else
            {
                ctlr = GetControllerInstance(controllerType);
            }

            
              


            System.Web.Mvc.Controller controller = (ctlr as System.Web.Mvc.Controller);

            if (controller != null && entry != null)
            {
                controller.ViewEngine = new ScaffoldWebFormViewEngine(entry.Views);
            }
            
            
            

            return ctlr;

        }
    }
}
